import "./reset.css";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { cloneDeep, deviceDetection, getKeyList } from "@pureadmin/utils";
import { computed, onMounted, reactive, ref, type Ref } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

export function useUserHooks() {
  return {
    switchStyle: ref({
      width: "58px",
      height: "30px"
    })
  };
}
export function useUser(tableRef: Ref) {
  const form = reactive({
    userName: "",
    userId: "",
    status: "",
    SearchTerm: "",
    OrderBy: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = useUserHooks();
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "用户名称",
      prop: "userName",
      minWidth: 130
    },
    {
      label: "用户编号",
      prop: "userCode",
      minWidth: 130
    },
    {
      label: "联系人",
      prop: "contactPerson",
      minWidth: 130
    },
    {
      label: "电话",
      prop: "phone",
      minWidth: 130
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="正常"
          inactive-text="禁用"
          inline-prompt
          style={switchStyle.value}
        />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  //修改
  function handleUpdate(row) {
    console.log(row);
  }
  //删除
  function handleDelete(row) {
    handleRemoveUser([row.userName]).then(res => {
      if (res) {
        message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
        onSearch();
      }
    });
  }
  //分页变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => {
      return item.Id;
    });
    handleRemoveUser(listIds).then(res => {
      if (res) {
        message(`已删除用户编号为 ${getKeyList(curSelected, "Name")} 的数据`, {
          type: "success"
        });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
      }
    });
  }
  //删除调用
  function handleRemoveUser(listIds) {
    return new Promise(resolve => {
      const params = {
        Ids: listIds
      };
      loading.value = true;
      http
        .post(changeHttpLink("/api/User/batch-delete"), {
          data: params
        })
        .then((res: any) => {
          loading.value = false;
          if (res.Success) {
            resolve(true);
          } else {
            message(res.Message, { type: "error" });
            resolve(false);
          }
        })
        .catch(err => {
          loading.value = false;
          message(err.message, { type: "error" });
          resolve(false);
        });
    });
  }
  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  //获取、搜索列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage, //int
      pageSize: pagination.pageSize, //int
      OrderBy: form.OrderBy, //string
      IsDesc: false, //boolean
      SearchTerm: form.SearchTerm, //string
      tenantId: 1 //int
    };
    http
      .post(changeHttpLink("/api/User"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  //新增、修改
  function openDialog(type = "新增", row = {}) {
    addDialog({
      title: `${type}用户`,
      props: {
        form: cloneDeep(row),
        type
      },
      width: "500px",
      draggable: true,
      contentRenderer: () => editForm,
      beforeSure: done => {
        done();
        onSearch();
      }
    });
  }

  // 初始化
  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
